<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>
        字典管理
    </title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <link rel="stylesheet" th:href="@{/assets/admin/css/font.css}">
    <link rel="stylesheet" th:href="@{/assets/admin/css/xadmin.css}">
    <script th:src="@{/assets/admin/lib/layui/layui.js}" charset="utf-8"></script>
    <script type="text/javascript" th:src="@{/assets/admin/js/xadmin.js}"></script>
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style type="text/css">
        .layui-form-switch {
            margin-top: 8px;
        }
        .layui-tree-checked{
            background-color:#d5e8fc;
        }

    </style>
</head>
<body>
<div class="x-nav">
           <span class="layui-breadcrumb">
              <a><cite>首页</cite></a>
              <a><cite>系统管理</cite></a>
              <a><cite>字典管理</cite></a>
            </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
       onclick="location.reload()" title="刷新">
        <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i></a>
</div>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md3">
            <div class="layui-card">
                <div class="layui-card-body">
                    <div class="layui-btn-group">
                        <button type="button" id="addBtn" class="layui-btn layui-btn-radius layui-btn-normal">新增</button>
                        <button type="button" id="editBtn" class="layui-btn layui-btn-radius">编辑</button>
                        <button type="button" id="deleteBtn" class="layui-btn layui-btn-radius layui-btn-danger">删除</button>
                    </div>
                    <div id="dict_tree">
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-col-md9">
            <div class="layui-card">
                <div class="layui-card-body">
                    <form class="layui-form" action="" lay-filter="query_user_form">
                        <input type="hidden" id="parentId" name="parentId" />
                        <div class="layui-inline layui-show-xs-inline-block ">
                            <input type="text" name="dictDataName" placeholder="请输入数据名" autocomplete="off"
                                   class="layui-input" id="dictDataName">
                        </div>
                        <div class="layui-inline layui-show-xs-inline-block">
                            <select id="status" name="status">
                                <option value="">--请选择状态--</option>
                                <option value="1">有效</option>
                                <option value="0">无效</option>
                            </select>
                        </div>
                        <div class="layui-inline layui-show-xs-inline-block">
                            <button class="layui-btn" lay-submit lay-filter="sreach">
                                <i class="layui-icon">&#xe615;</i>查询</button>
                        </div>
                    </form>
                    <div class="layui-btn-group">
                        <button type="button" class="layui-btn layui-btn-sm" id="addDataBtn">
                            <i class="layui-icon">&#xe654;</i>
                        </button>
                        <button type="button" class="layui-btn layui-btn-sm" id="eidtDataBtn">
                            <i class="layui-icon">&#xe642;</i>
                        </button>
                        <button type="button" class="layui-btn layui-btn-sm" id="deleteDataBtn">
                            <i class="layui-icon">&#xe640;</i>
                        </button>
                    </div>
                    <table id="dict_table">
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="layui-container">
</div>
</body>
<script th:src="@{/assets/admin/js/jquery.min.js}"></script>
<script th:replace="systemCommon/HarinCommon :: commonJs"></script>
<script>
    let checkedDictParentId = 0;
    let dictTable = null;
    layui.use(['tree','laydate', 'element', 'form', 'layer', 'table'], function () {
        $ = layui.jquery;//jquery
        laydate = layui.laydate;//日期插件
        lement = layui.element; //面包导航
        layer = layui.layer;    //弹出层
        tree = layui.tree;
        form = layui.form;
        table = layui.table;
        tree_obj = {
            elem: '#dict_tree',
            data: null,
            id: 'dict_tree_id',
            showCheckbox: true,      //是否显示复选框
            onlyIconControl: true,    //有单击事件，所以这个应该关闭
            showLine: true,           //是否开启连接线。默认 true，若设为 false，则节点左侧出现三角图标。
            //edit: ['del'],          //是否开启节点的操作图标
            accordion: true,
            text: {
                defaultNodeName: '未命名',     //节点默认名称
                none: '无数据'                 //数据为空时的提示文本
            },
            click: function (obj) {             //单击事件
                $(".layui-tree-checked").removeClass("layui-tree-checked");
                obj.elem.find(".layui-tree-txt").addClass("layui-tree-checked");
                checkedDictParentId = obj.data.id;
                $("#parentId").val(obj.data.id);
                if( dictTable!= null){
                    //清空搜索条件
                    $("#dictDataName").val("");
                    $("#status").val("");
                    //重新加载table
                    dictTable.reload({
                        where:{
                            "parentId":checkedDictParentId,
                            "dataName":"",
                            "status":""
                        }
                    });
                }
            }
        };

        dictTable = table.render({
            elem: '#dict_table',
            url: '/system/getDictDataByVo', //数据接口
            method: "get",
            where: {     //请求参数
                "parentId": 0
            },
            parseData: function (res) { //res 即为原始返回的数据
                var data = res.result;
                //console.log(data.records);
                //console.log(typeof data.records);
                return {
                    "code": res.code, //解析接口状态
                    // "msg": res.message, //解析提示文本
                    "count": data.total, //解析数据长度
                    "data": data.records //解析数据列表
                };
            },
            response: {//重新定义规则
                //statusName: 'status', //规定数据状态的字段名称，默认：code
                statusCode: 200, //规定成功的状态码，默认：0
                //msgName: 'hint', //规定状态信息的字段名称，默认：msg
                //countName: 'total', //规定数据总数的字段名称，默认：count
                //dataName: 'rows' //规定数据列表的字段名称，默认：data
            },
            page: true, //开启分页
            limits: [10, 20, 50],//可选条目数
            toolbar: false,//若需要“列显示隐藏”、“导出”、“打印”等功能，则必须开启该参数
            loading: true, //加载动画
            cols: [
                [ //表头
                    {type: 'checkbox', fixed: 'left',width:80},
                    {field: 'no', title: '序号', width: 80,fixed: 'left',  sort: true },
                    {field: 'dataName', title: '数据名',width:150},
                    {field: 'dataValue', title: '数据值', width: 150,  sort: true },
                    {field: 'createTime', title: '创建时间',width:145,sort: true,templet : "<div>{{layui.util.toDateString(d.createTime, 'yyyy年MM月dd日 HH:mm:ss')}}</div>"},
                    {field: 'effectiveDate', title: '失效时间',width:145,sort: true,templet : "<div>{{layui.util.toDateString(d.effectiveDate, 'yyyy年MM月dd日 HH:mm:ss')}}</div>"},
                    {field: 'state', title: '状态', templet: '#switchStatus', width: 95,unresize: true},
                    {field: 'operation', title:'操作', toolbar: '#barDemo',width:230,fixed: 'right',unresize: true}
                ]
            ]
        });

        //以上模块根据需要引入
        // tree.render(tree_obj);
        getData();
        form.on('submit(sreach)', function (data) {
            dictTable.reload({
                where: {
                    "parentId": data.field.parentId,
                    "dataName": data.field.dictDataName,
                    "status": data.field.status
                },
                page:{
                    curr:1
                }
            });
            return false;
        });
        //
        $("#addBtn").on('click',function(){
            openLayer("新增字典","/system/addDictUI",480,350,false,function(){
                let checked = tree.getChecked('dict_tree_id');
                getData();
                if(!isEmpty(checked) &&checked.length != 0){
                    $.each(checked,function(index,item){
                        tree.setChecked('dict_tree_id',item.id);
                    });
                }
            });
        });

        $("#editBtn").on('click',function(){
            let checked = tree.getChecked('dict_tree_id');
            if(checked.length == 0 ){
                    layer.msg('必须选择一条字典数据！');
                    return;
            }else if(checked.length > 1){
                layer.msg('不能同时选择多条数据！');
                return;
            }
            openLayer("修改字典","/system/addDictUI?id="+checked[0].id,480,350,false,function(){
                let checked = tree.getChecked('dict_tree_id');
                getData();
                if(!isEmpty(checked) &&checked.length != 0) {
                    $.each(checked, function (index, item) {
                        tree.setChecked('dict_tree_id', item.id);
                    });
                }
                })

        });
        $("#deleteBtn").on("click",function(event){
            layer.confirm("确定删除吗？",function(){
                    let checked = tree.getChecked('dict_tree_id');
                    if(checked.length == 0 ){
                        layer.msg('必须选择一条字典数据！');
                        return;
                    }
                    //获取对象数组中的id字段并组成新数组
                    let ids = Array.from(checked,e=>e.id);

                    $.ajax({
                        url: "/system/deleteDicts",
                        type:"delete",
                        data:{"ids":ids},
                        success:function(data){
                            if (data.code == 200) {
                                layer.alert(data.message, {icon: 6}, function (index) {
                                    getData();
                                    // 获得frame索引
                                    //var index = parent.layer.getFrameIndex(window.name);
                                    //关闭当前frame
                                    layer.close(index);
                                });
                            } else {
                                layer.alert(data.message, {icon: 5}, function (index) {
                                    getData();
                                    // 获得frame索引
                                    //var index = parent.layer.getFrameIndex(window.name);
                                    //关闭当前frame
                                    layer.close(index);
                                });
                            }
                        }
                    });
                });
            });

        $("#addDataBtn").on('click',function(event){
            let parentId = $("#parentId").val();
            if(isEmpty(parentId)){
                layer.msg('必须选择一条字典数据！');
            }else {
                openLayer("新增字典数据", "/system/gotoAddDictData?parentId=" + parentId, 560, 500, false, function(){
                    dictTable.reload({
                        where:{
                            "parentId":$("#parentId").val(),
                            "dataName":$("#dataName").val(),
                            "status":$("#status").val()
                        }
                    })
                });
            }
        });
        $("#eidtDataBtn").on('click',function(event){
            //console.log(tree);
            let checkStatus = table.checkStatus("dict_table").data;
            //console.log(checkStatus);
            if(checkStatus.length == 0 ){
                layer.msg("未选择需要修改的字典数据!");
            }else if (checkStatus.length > 1){
                layer.msg("只允许选择一条字典数据!");
            }else{
                console.log(checkStatus);
                openLayer("修改字典数据","/system/gotoEditDictData?dictDataId="+checkStatus[0].id, 560, 500, false, function() {
                    dictTable.reload({
                        where: {
                            "parentId": $("#parentId").val(),
                            "dataName": $("#dataName").val(),
                            "status": $("#status").val()
                        }
                    })
                });
            }
        });
        $("#deleteDataBtn").on('click',function(event){
            let checkStatus = table.checkStatus("dict_table").data;
            //console.log(checkStatus);
            if(checkStatus.length == 0 ){
                layer.msg("未选择需要修改的字典数据!");
            }
            else {
            layer.confirm("确定删除吗？",function(){
              $.ajax({
                  url : "/system/deleteDictData",
                  type: "delete",
                  data:JSON.stringify(checkStatus),
                  contentType: 'application/json',//这个必须是这个格式
                  success:function(data){
                          if (data.code == 200) {
                              layer.alert(data.message, {icon: 6}, function (index) {
                                  dictTable.reload({
                                      where:{
                                          "parentId":$("#parentId").val(),
                                          "dataName":$("#dataName").val(),
                                          "status":$("#status").val()
                                      }
                                  })
                                  layer.close(index);
                              });
                          } else {
                              layer.alert(data.message, {icon: 5}, function (index) {
                                  dictTable.reload({
                                      where:{
                                          "parentId":$("#parentId").val(),
                                          "dataName":$("#dataName").val(),
                                          "status":$("#status").val()
                                      }
                                  })
                                  layer.close(index);
                              });
                          }
                      }
                  })
                });
            }
        });
    });

    function openLayer(title, url, w, h, full, backFun) {
        if (backFun == null || !backFun) {
            Harin.openLoyer1(title, url, w, h, full);
        } else {
            //调用自己封装的方法。
            Harin.openLoyer1(title, url, w, h, full, backFun);
        }
    }


    //批量删除提交
    function delAll() {
        layer.confirm('确认要删除吗？', {icon: 3, title: '提示信息'}, function (index) {
            //捉到所有被选中的，发异步进行删除
            layer.msg('删除成功', {icon: 1});
        });
    }

    /*获取后台的菜单数据*/
    function getData() {
        $.ajax({
            url: "/system/getDictList",    //后台数据请求地址
            type: "post",
            async: false,
            success: function (resut) {
                res_data = resut.result;
                tree_obj.data = res_data;
                tree.render(tree_obj);
            }

        });
    }
</script>
</html>